'use strict'

const path = require('path')
const {app, ipcMain, Notification} = require('electron')

const UpdateHandler = require('./browser/lib/update')
const Common = require('./common')
const AppConfig = require('./configuration')

const SplashWindow = require('./browser/splash')
const WeChatWindow = require('./browser/wechat')
const AppTray = require('./browser/app_tray')

const log4js = require('log4js')

class ElectronjsWeChat {
  constructor() {
    this.wechatWindow = null
    this.splashWindow = null
    this.tray = null
    this.logger = log4js.getLogger("INDEX")
    this.logger.level = AppConfig.isOK() ? AppConfig.readSettings("logger-level") : "ALL"
  }

  init() {
    this.initIPC()
    this.initApp()
    if(this.checkInstance()) {
      app.whenReady().then(() => {
        this.logger.debug("app ready")
        this.createSplashWindow()
        this.createWeChatWindow()
        this.createTray()
      })
    } else {
      this.logger.debug("check instance return false")
      app.quit()
    }
  }

  checkInstance() {
    this.logger.debug("check instance")
    if (AppConfig.readSettings('multi-instance')) return true
    return !app.requestSingleInstanceLock()
  }

  initApp() {
    this.logger.debug("register app event")
    app.on('activate', () => {
      this.logger.debug("app activate event")
      if (this.wechatWindow == null) {
        this.createWeChatWindow()
      } else {
        this.wechatWindow.show()
      }
    })
    
    app.on('second-instance', (event, commandLine, workingDirectory) => {
      this.logger.debug("app second instance event")
      if(this.splashWindow && this.splashWindow.isShown){
        this.splashWindow.show()
        return
      }
      if(this.wechatWindow){
        this.wechatWindow.show()
      }
    })

    app.on('window-all-closed', (event) => {
      this.logger.debug("window-all-closed")
      app.quit()
    })
  }

  initIPC() {
    ipcMain.on('badge-changed', (event, num) => {
      this.logger.trace(`ipc badge changed event: ${num}`)
      if (process.platform == "darwin") {
        app.dock.setBadge(num)
        if (num) {
          this.tray.setTitle(` ${num}`)
        } else {
          this.tray.setTitle('')
        }
      } else if (process.platform === "linux" || process.platform === "win32") {
          app.setBadgeCount(num * 1)
          this.tray.setUnreadStat((num * 1 > 0)? 1 : 0)
      }
    })

    ipcMain.on('user-logged', () => {
      this.logger.debug('ipc user logged event')
      this.wechatWindow.resizeWindow(true, this.splashWindow)
    })

    ipcMain.on('wx-rendered', (event, isLogged) => {
      this.logger.debug('ipc wx rendered event')
      this.wechatWindow.resizeWindow(isLogged, this.splashWindow)
    })

    ipcMain.on('log', (event, message) => {
      this.logger.debug(message)
    })

    ipcMain.on('reload', (event, repetitive) => {
      this.logger.debug("ipc reload event")
      if (repetitive) {
        this.wechatWindow.reload(repetitive)
      }
    })

    ipcMain.on('update', (event, message) => {
      this.logger.debug("ipc update event")
      let updateHandler = new UpdateHandler()
      updateHandler.checkForUpdate(`v${app.getVersion()}`, false)
    })

    ipcMain.on('notify', (event, message) => {
      this.logger.debug(message.body)
      new Notification(message).show()
    })

    ipcMain.handle('version', (event) => {
      let result = {}
      result.electronjs_wechat_version = app.getVersion()
      result.electronjs_version = process.versions['electron']
      result.nodejs_version = process.vesion
      return result
    })
  }

  createTray() {
    this.logger.debug("app create tray")
    this.tray = new AppTray(this.splashWindow, this.wechatWindow)
  }

  createSplashWindow() {
    this.logger.debug("app create splash")
    this.splashWindow = new SplashWindow()
    this.splashWindow.show()
  }

  createWeChatWindow() {
    this.logger.debug("app create wechat")
    this.wechatWindow = new WeChatWindow()
  }
}

new ElectronjsWeChat().init()
